﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using System;
using AutoDeploy.ConfigModel;

namespace AutoDeploy.Filters
{
    public class AuthorizationFilter : Attribute,IAuthorizationFilter
    {
        private readonly string _userAgent;
        private readonly string _secretKey;
        private readonly Hosting _hostConfig;

        public AuthorizationFilter(IConfiguration configuration)
        {
            _hostConfig = new Hosting();
            configuration.GetSection("Hosting").Bind(_hostConfig);
            if(_hostConfig.CodePlatform.Equals("GitHub"))
            {
                _userAgent = "GitHub-Hookshot";
                _secretKey = "X-Hub-Signature";
            }
            else
            {
                _userAgent = "git-oschina-hook";
                _secretKey = "X-Gitee-Token";
            }
        }
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            #region 授权
            // 校验请求头
            if (context.HttpContext.Request.Headers["User-Agent"].ToString().IndexOf(_userAgent)>-1)
            {
                // 校验密钥
                if (!context.HttpContext.Request.Headers[_secretKey].ToString().Equals(_hostConfig.CodeSecret))
                {
                    context.Result = new JsonResult(new { code = 401, msg = "非法密钥" });
                    return;
                }
            }
            else
            {
                context.Result = new JsonResult(new { code = 401, msg = "非法请求头" });
                return;
            }
            #endregion

        }
    }
}
